package deque

import "util"

const InitCap = 16

type Element interface{}

/*
双端队列
*/
type Deque struct {
	vals []Element
}

func New() *Deque {
	dq := new(Deque)
	dq.vals = make([]Element, 0, InitCap)
	return dq
}

func (this *Deque) Size() int {
	return len(this.vals)
}

func (this *Deque) Empty() bool {
	return len(this.vals) == 0
}

func (this *Deque) Clear() {
	this.vals = make([]Element, 0, InitCap)
}

func (this *Deque) AddLast(e Element) {
	this.vals = append(this.vals, e)
}

func (this *Deque) AddFirst(e Element) {
	this.vals = append([]Element{e}, this.vals...)
}

func (this *Deque) RemoveLast() Element {
	if this.Empty() {
		return nil
	}
	n := len(this.vals)
	ret := this.vals[n-1]
	this.vals = this.vals[:n-1]
	return ret
}

func (this *Deque) RemoveFirst() Element {
	if this.Empty() {
		return nil
	}
	ret := this.vals[0]
	this.vals = this.vals[1:]
	return ret
}

func (this *Deque) GetLast() Element {
	if this.Empty() {
		return nil
	}
	return this.vals[len(this.vals)-1]
}

func (this *Deque) GetFirst() Element {
	if this.Empty() {
		return nil
	}
	return this.vals[0]
}

func (this *Deque) String() string {
	vals2 := make([]interface{}, len(this.vals))
	for i, val := range this.vals {
		vals2[i] = val
	}
	return "Head" + util.ToString(vals2) + "Tail"
}
